import {httpUrl} from './config.js'

const request = (url ,params) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: httpUrl + url,
			data: params,
			header: {
				Authorization: uni.getStorageSync('token')
			},
			method: params.method || 'POST'
		}).then(response => {
			let [err, res] = response
			resolve(res.data)
		}).catch(error => {
			let [err, res] = error
			reject(err)
		})
	})
}

const uploadFile = (url, params) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中...'
		})
		uni.uploadFile({
			url: httpUrl + url,
			filePath: params.file,
			name: 'file',
			formData: {type: params.type ? params.type : 1}
		}).then(response => {
			uni.hideLoading()
			let [err, res] = response
			res = JSON.parse(res.data)
			resolve(res)
		}).catch(error => {
			uni.hideLoading()
			let [err, res] = error
			reject(err)
		})
	})
}

const uploadFileMore = (url, params) => {
	let files = []
	params.files.forEach(res => {
		files.push({
			name: 'file[]',
			uri: res
		})
	})
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中...'
		})
		uni.uploadFile({
			url: httpUrl + url,
			files: files,
			formData: {type: params.type}
		}).then(response => {
			uni.hideLoading()
			let [err, res] = response
			res = JSON.parse(res.data)
			resolve(res)
		}).catch(error => {
			uni.hideLoading()
			let [err, res] = error
			reject(err)
		})
	})
}

export const send_code = (params) => request('api/send_code', params)